/*
 * @Description: 查看申请弹窗
 * @Author: Rfan
 * @Date: 2022-02-24 16:16:12
 * @LastEditTime: 2023-02-28 11:04:22
 */

import { useEffect, useState } from 'react';
import { Button, Form, Input, Modal } from 'antd';
import classNames from 'classnames/bind';
import { IDealTaskParams, ITaskListResolve } from '@/api/workFlow/task';
import { appState } from '@/store/mobx';
import { useMyApprovalsContext } from '../../../contexts/MyApprovalsContext';
import type { ICommonDialog } from '@/interfaces/global';
import styles from './styles/index.module.scss';

const cx = classNames.bind(styles);

interface IApprovalDialogProps extends ICommonDialog {
  data: ITaskListResolve;
}

const ApprovalDialog = (props: IApprovalDialogProps) => {
  const { visible, data, onClose } = props;
  const { submitApprovalFunc } = useMyApprovalsContext();
  const [form] = Form.useForm();
  const [submitState, setSubmitState] = useState<number>(0);

  useEffect(() => {
    if (visible) {
      //
    }
  }, [visible]);

  // 提交表单
  const submitFunc = (state: number) => {
    console.log('submit');
    setSubmitState(state);
    form.submit();
  };

  /**
   * @description: 审批通过
   */
  const submitAgree = () => {
    submitFunc(1);
  };

  /**
   * @description: 审批拒绝
   */
  const submitDisagree = () => {
    submitFunc(2);
  };

  const handleFinished = (values: { comment: string }) => {
    console.log({ submitState });
    const param: IDealTaskParams = {
      ...values,
      processInstanceId: data.processInstanceId,
      taskId: data.task?.taskId,
      userId: appState.userInfo.id
    };

    submitApprovalFunc(param, submitState).then(() => {
      onCancel();
    });
  };

  const onCancel = () => {
    onClose();
  };

  return (
    <Modal
      title="审批"
      visible={visible}
      width={800}
      destroyOnClose
      onCancel={onCancel}
      footer={[
        <Button key="close" onClick={onCancel}>
          关闭
        </Button>,
        <Button key="back" onClick={submitDisagree}>
          拒绝
        </Button>,
        <Button key="submit" type="primary" onClick={submitAgree}>
          同意
        </Button>
      ]}
    >
      <div className={cx('result')}>
        <Form form={form} colon={false} onFinish={handleFinished}>
          <Form.Item name="comment" label="审批意见">
            <Input.TextArea rows={3} />
          </Form.Item>
        </Form>
      </div>
    </Modal>
  );
};

export default ApprovalDialog;
